package host.skiree.nettydemo.client;

import host.skiree.nettydemo.client.handler.DemoClientHandler;
import host.skiree.nettydemo.protocol.MessageCodecSharable;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author gcl
 * @date 2022/9/19 9:18
 */
@Slf4j
public class NettyClient {
    public static void main(String[] args) {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        try{
            Channel channel = new Bootstrap()
                    // 客户端配置链接超时 0.3秒未连接到服务器则超时
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                    .group(nioEventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(0,2,0));
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(10240, 11,4,1,0));
//                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new MessageCodecSharable());
                            ch.pipeline().addLast(new DemoClientHandler());
                        }
                    })
                    .connect(new InetSocketAddress("127.0.0.1", 8080))
                    .sync()
                    .channel();
            channel.closeFuture().sync().addListener(future -> {
                log.warn("客户端已关闭");
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            nioEventLoopGroup.shutdownGracefully();
        }
    }
}
